// stores/counter.ts
import { defineStore } from 'pinia'
import { ref, computed, watchEffect } from 'vue'
export interface ContentApiResponse {
  id: string;
  order: number;
  chinese: string;
  english: string;
  mark: string;
}
export interface courseApiResponse {
  title: string;  // 课程标题
  description: string;  // 课程描述
  id: string;  // 课程ID
}
export interface chapterApiResponse {
  id: string;
  title: string;
  description: string;
  course: courseApiResponse;
  order: number;
  content: ContentApiResponse[];
  coursePackId: string;
  completionCount: number;
  statementIndex: number;
  video: string;
}
export const useCourseStore = defineStore('counter', () => {
  const courseData = ref<chapterApiResponse | null>(null)  // 默认数据
  const currentData = ref<ContentApiResponse | null>(null)
  const currentIndex = ref(0)
  const errIds = ref<string[]>([])
  const studyType = ref('')
  // 更新 currentData，依赖于 currentIndex
  watchEffect(() => {
    currentData.value = courseData.value?.content[currentIndex.value] || null
  })
  // 计算单词数
  const words = computed(() => {
    return currentData.value?.english.split(" ") || []
  })
  const findContentCount = () => {
    return courseData.value?.content.length || 0
  }
  function isEnd() {
    return currentIndex.value >= findContentCount() - 1
  }
  // 查找下一题
  function findNext() {
    const nextIndex = currentIndex.value + 1
    return nextIndex < findContentCount() ? 1 : undefined
  }
  // 重置
  function resetCurrentIndex() {
    currentIndex.value = 0
    errIds.value = []
  }
  // 记录错题
  function recordErrId() {
    const id = currentData.value?.id || ""
    if (!errIds.value.includes(id)) {
      errIds.value.push(id)
    }
  }

  // 下一题
  function toNextData() {
    if (findNext()) {
      currentIndex.value += 1
    }
  }

  function toIndexData(index: number) {
    currentIndex.value = index
  }

  function toPrevData() {
    console.log('触发触发')
    if (currentIndex.value > 0) {
      currentIndex.value -= 1
    }
  }
  function getPrevEnglish() {
    if(currentIndex.value === 0)return;
    return courseData.value?.content[currentIndex.value - 1].english || ""
  }
  function getEnglish() {
    return currentData.value?.english || ""
  }
  function computerRatio() {
    return ((currentIndex.value + 1) * 100) / findContentCount();
  }
  return {
    toPrevData,
    toIndexData,
    getEnglish,
    getPrevEnglish,
    studyType,
    computerRatio,
    errIds,
    recordErrId,
    words,
    findContentCount,
    currentData,
    courseData,
    resetCurrentIndex,
    isEnd,
    findNext,
    currentIndex,
    toNextData,
  }
})
